<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/28
 * Time: 10:41
 */

namespace app\api\controller\v1;

use app\api\Model\SendCode as SendCodeModel;
use app\api\Model\User as UserModel;
use app\api\Model\UserDetailMoney as UserDetailMoneyModel;
use app\api\Model\UserBank as UserBankModel;
use app\api\Model\UserAli as UserAliModel;
use app\api\Model\UserBank;
use app\api\Model\UserDetailMoney;
use app\api\Model\UserIncome as UserIncomeModel;
use app\api\validate\IDMustBePostiveInt;
use app\api\validate\UserValidate;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UserException;

use think\Db;

class User
{

    /**
     * @api {post} /user/login 用户登录
     * @apiName login
     * @apiGroup User
     *
     * @apiParam {Number} mobile 手机号.
     * @apiParam {varchar} password 密码
     *
     * @apiSuccess {String} id 用户id
     * @apiSuccess {String} mobile 手机号
     * @apiSuccess {String} pic 头像
     * @apiSuccess {String} username 用户昵称
     * @apiSuccess {String} address 地址
     * @apiSuccess {String} pay_money 消费金额
     * @apiSuccess {String} money 余额
     */
    public function login()
    {
        if (request()->isPost()) {
            $validate = new UserValidate();
            $validate->goCheck();

            $data = $validate->getDataByRule(input('post.'));

            $data['password'] = md5(md5(input('post.password')));
            $user = new UserModel();
            $info = $user->where($data)->find();

            if ($info) {
                return $info;
            } else {
                throw new UserException();
            }
        }

    }

    /**
     * @api {post} /user/userRegister 注册
     * @apiName userRegister
     * @apiGroup User
     *
     * @apiParam {Number} mobile 手机号
     * @apiParam {varchar} password 密码
     * @apiParam {varchar} code 推荐码
     *
     * @apiSuccess {String}  code =1 注册成功
     *
     * @apiErrorExample {string} Error-Response:
     * code=0: 注册失败
     */
    public function userRegister()
    {
        if (request()->isPost()) {
            $validate = new UserValidate();
            $validate->goCheck();

            $data = $validate->getDataByRule(input('post.'));

            $data['password'] = md5(md5(input('post.password')));
            $data['username'] = '用户_' . substr($data['mobile'], -4);
            $data['code'] = str_pad(mt_rand(0, 999999), 6, "0", STR_PAD_BOTH);//邀请码
            $data['create_time'] = strtotime(date('Y-m-d h:i:s', time()));//用户注册时间
            $code = input('post.code');
            $user = new UserModel();
            $info = $user->insertGetId($data);

            // 判断是否存在code码
            if ($code) {
                $res = Db::name('user')->where('code', $code)->find();
                if ($res && $res['invite_id'] == 0)
                    Db::name('user')->where('code', $code)->update(['invite_id' => $info]);
            }


            if ($info) {
                return json(['code' => 1, 'data' => $info, 'msg' => '注册成功']);
            } else {
                return json(['code' => 0, 'msg' => '注册失败']);
            }
        }
    }

    /**
     * @api {post} /user/sendRegisterCode 发送注册验证码
     * @apiName sendRegisterCode
     * @apiGroup User
     *
     * @apiParam {Number} mobile 手机号
     *
     * @apiSuccess {String}  code 验证码
     * @apiSuccess {String}  msg 提示信息
     *
     */
    //注册发送验证码
    public function sendRegisterCode()
    {
        if (request()->isPost()) {
            $mobile = input('post.mobile');
            $tpl_id = '85768';
            $code = str_pad(mt_rand(0, 999999), 6, "0", STR_PAD_BOTH);
            $send_code = new SendCodeModel();
            $info = $send_code->send($mobile, $tpl_id, $code);

            return json(['code' => $code, 'msg' => $info]);
        }
    }

    /**
     * @api {post} /user/sendPasswordCode 找回密码发送验证码
     * @apiName sendPasswordCode
     * @apiGroup User
     *
     * @apiParam {Number} mobile 手机号
     *
     * @apiSuccess {String}  code 验证码
     * @apiSuccess {String}  msg 提示信息
     *
     */
    //找回密码发送验证码
    public function sendPasswordCode()
    {
        if (request()->isPost()) {
            $mobile = input('post.mobile');
            $tpl_id = '85769';
            $code = str_pad(mt_rand(0, 999999), 6, "0", STR_PAD_BOTH);
            $send_code = new SendCodeModel();
            $info = $send_code->send($mobile, $tpl_id, $code);

            return json(['code' => $code, 'msg' => $info]);
        }
    }

    /**
     * @api {post} /user/updateUserPassword  用户重置密码
     * @apiName updateUserPassword
     * @apiGroup User
     *
     * @apiParam {Number} mobile 手机号
     * @apiParam {Number} password 密码
     *
     * @apiSuccess {String}  code  1代表成功  0代表失败
     * @apiSuccess {String}  msg 提示信息
     *
     */
    //用户重置密码
    public function updateUserPassword()
    {
        if (request()->isPost()) {
            $mobile = input('post.mobile');
            $data['password'] = md5(md5(input('post.password')));

            $info = UserModel::where('mobile', $mobile)->update($data);
            if ($info) {
                return json(['code' => 1, 'msg' => '修改成功']);
            } else {
                return json(['code' => 0, 'msg' => '修改失败']);
            }
        }
    }


    /**
     * @api {post} /user/checkPhone 验证手机号是否存在
     * @apiName checkPhone
     * @apiGroup User
     *
     * @apiParam {Number} mobile 手机号
     *
     * @apiSuccess {String}  code=0
     *
     * @apiErrorExample {string} Error-Response:
     * 1 : 手机号已经注册
     */
    public function checkPhone()
    {
        if (request()->isPost()) {
            $mobile = (input('post.mobile'));
            $check_phone = new UserModel();
            $info = $check_phone->check_phone($mobile);
            if ($info) {
                return json(['code' => 1, 'msg' => '手机号已经注册']);
            } else {
                return json(['code' => 0, 'msg' => '手机号未注册']);
            }
        }
    }

    /**
     * @api {post} /user/erjiUser 二级会员
     * @apiName erjiUser
     * @apiGroup User
     * @apiParam {int} id 用户id
     *
     * @apiSuccess {String} code=1 返回二级会员信息
     * @apiSuccess {String} id 用户id
     * @apiSuccess {String} mobile 手机号
     * @apiSuccess {String} username 用户昵称
     * @apiSuccess {String} address 地址
     * @apiSuccess {String} pay_money 消费金额
     * @apiSuccess {String} money 余额
     *
     *
     * @apiErrorExample {string} Error-Response:
     * code =0: 没有二级会员
     */
    public function erjiUser()
    {

        if (request()->isPost()) {

            $id = (input('post.id'));
            $erjiUser = new UserModel();
            $info = $erjiUser->erjiUser($id);
            if ($info != null) {
                return json(['code' => 1, 'data' => $info, 'msg' => '二级会员信息']);
            } else {
                return json(['code' => 0, 'msg' => '暂无信息']);
            }
        }
    }

    /**
     * @api {post} /user/sanjiUser 三级会员
     * @apiName sanjiUser
     * @apiGroup User
     *
     * @apiParam {int} id 用户id
     *
     * @apiSuccess {String} code=1 返回三级会员信息
     * @apiSuccess {String} id 用户id
     * @apiSuccess {String} mobile 手机号
     * @apiSuccess {String} username 用户昵称
     * @apiSuccess {String} address 地址
     * @apiSuccess {String} pay_money 消费金额
     * @apiSuccess {String} money 余额
     *
     *
     * @apiErrorExample {string} Error-Response:
     * code =0: 没有三级会员
     */
    public function sanjiUser()
    {

        if (request()->isPost()) {

            $id = (input('post.id'));
            $User = new UserModel();
            $erjiUser = $User->erjiUser($id);
//            return $erjiUser;
            $info = [];
            foreach ($erjiUser as $key) {

                $id1 = $key['id'];
                $sanjiUser = $User->sanjiUser($id1);

                if (!$sanjiUser->isEmpty()) {
                    $info[] = $sanjiUser;
                }

            }
            if ($info != null) {
                return json(['code' => 1, 'data' => $info, 'msg' => '三级会员信息']);
            } else {
                return json(['code' => 0, 'msg' => '暂无三级会员']);
            }
        }
    }

    /**
     * @api {get} /user/getWchatQrcode 获取推广码
     * @apiName getWchatQrcode
     * @apiGroup User
     *
     * @apiParam {string} code 推荐码
     *
     * @apiSuccess {String} code=200 成功
     * @apiSuccess {String} data  base64图片
     *
     *
     */

    public function getWchatQrcode($level = 3, $size = 4)
    {

        vendor('phpqrcode.phpqrcode');
        $code = (input('get.code'));
        $url = 'http://www.yingtouxiaoli.com/' . '?' . "code" . "=" . $code;
//        var_dump($url);
//        die;
        $errorCorrectionLevel = 'H';//容错级别
        $matrixPointSize = 5;//图片大小慢慢自己调整，只要是int就行
        $path = '../../images/';
        $QR = $QRB = $path . rand(10000, 99999) . time() . ".png";

        \QRcode::png($url, $QR, $errorCorrectionLevel, $matrixPointSize, 2);

        //引入第三方
        Vendor('phpqrcode.phpqrcode');
        $errorCorrectionLevel = intval($level);//容错级别
        $matrixPointSize = intval($size);//生成图片大小
        //实例化qrcode方法

        $object = new \QRcode();
        //打开缓冲区
        ob_start();
        $object->png($url, false, $errorCorrectionLevel, $matrixPointSize, 2);
        //这里就是把生成的图片流从缓冲区保存到内存对象上，使用base64_encode变成编码字符串，通过json返回给页面。
        $imageString = base64_encode(ob_get_contents());

        //关闭缓冲区
        ob_end_clean();
        //把生成的base64字符串返回给前端
        $data = array(
            'code' => 200,
            'data' => $imageString
        );
        return $data;
    }

    /**
     * @api {post} /user/setUserInfo 设置基本信息
     * @apiName setUserInfo
     * @apiGroup User
     *
     * @apiParam {int} id 用户id
     *
     * @apiParam {string} username 用户名
     * @apiParam {string} address 地址
     *
     * @apiSuccess {String} code=201 成功
     *
     */

    public function setUserInfo()
    {

        if (request()->isPost()) {
            $where['id'] = input('post.id');
            $data['username'] = input('post.username');
            $data['address'] = input('post.address');
            $user = new UserModel();
            $user->save($data, $where);
            return json(new SuccessMessage(), 201);
        }
    }


    /**
     * @api {post} /user/setUserLogo 设置头像
     * @apiName setUserLogo
     * @apiGroup User
     *
     * @apiParam {int} id 用户id
     *
     * @apiParam {base64} pic 头像
     *
     * @apiSuccess {String} code=201 成功
     *
     */
    public function setUserLogo()
    {
        if (request()->isPost()) {
            $where['id'] = input('post.id');
            $pic = input('post.pic'); //用户头像
            $tmp = preg_match('/^(data:\s*image\/(\w+);base64,)/', $pic, $result);
            if ($tmp) {
                $time = time(); //获得当前时间戳
                $type = $result[2];
                $new_file = "./images/{$time}.{$type}";
                $data['pic'] = ltrim($new_file, ".");
                file_put_contents($new_file, base64_decode(str_replace($result[1], '', $pic)));
            }
            $user = new UserModel();
            $user->save($data, $where);
            return json(new SuccessMessage(), 201);
        }
    }

    /**
     * @api {post} /user/getUserIncome 我的收益列表
     * @apiName getUserIncome
     * @apiGroup User
     *
     * @apiParam {int} user_id 用户id
     *
     * @apiParam {string} money 收入
     * @apiParam {string} note 说明
     * @apiParam {string} data.username 消费人
     * @apiSuccess {String} code=201 成功
     *
     */
    public function getUserIncome()
    {
        if (request()->isPost()) {
            $where['user_id'] = input('post.user_id');
            $result = UserIncomeModel::where($where)->with('user')->select();
            $result = $result->hidden(['user.mobile', 'user.address', 'user.pic', 'user.erji_money', 'user.code', 'user.sanji_money', 'user.pay_money', 'user.money']);
//            return $result;
//            $result =$result->hidden(['id']);
            if (!$result->isEmpty()) {
                return $result;
            } else {
                return json(['code' => 0, 'msg' => '暂无信息']);
            }
        }
    }

    /**
     * @api {post} /user/getUserInfo 获取用户信息
     * @apiName getUserInfo
     * @apiGroup User
     *
     * @apiParam {int} id 用户id
     *
     *
     * @apiSuccess {String} id 用户id
     * @apiSuccess {String} mobile 手机号
     * @apiSuccess {String} pic 头像
     * @apiSuccess {String} username 用户昵称
     * @apiSuccess {String} address 地址
     * @apiSuccess {String} pay_money 消费金额
     * @apiSuccess {String} money 余额
     *
     * @apiErrorExample {string} Error-Response:
     * 0 : 暂无信息
     */

    public function getUserInfo()
    {
        if (request()->isPost()) {

            $id = input('post.id');
            (new IDMustBePostiveInt())->goCheck();
            $info = UserModel::find($id);
            if ($info) {
                return $info;
            } else {
                return json(['code' => 0, 'msg' => '暂无信息']);
            }
        }
    }


    /**
     * @api {post} /user/addAlipay 用户添加支付宝
     * @apiName addAlipay
     * @apiGroup User
     *
     * @apiParam {int} user_id 用户id
     *
     * @apiParam {String} alipay_name 支付宝用户姓名
     * @apiParam {String} account 支付宝账号
     * @apiParam {String} telephone 支付宝电话
     *
     *  * @apiSuccess {String} 1 成功
     *
     * @apiErrorExample {string} Error-Response:
     * 0 : 已经添加过支付宝了
     * 2：添加失败
     */
    public function addAlipay()
    {
        $where['user_id'] = input('post.user_id');

        //验证是否已经添加
        $res = UserAliModel::where($where)->find();
        if ($res) {
            return json(['code' => 0, 'msg' => '已经添加过支付宝了']);
        } else {
            $data['user_id'] = input('post.user_id');
            $data['alipay_name'] = input('post.alipay_name');
            $data['account'] = input('post.account');
            $data['telephone'] = input('post.telephone');  //手机号
            $data['create_time'] = strtotime(date('Y-m-d h:i:s', time()));

            $user = new UserAliModel();
            $info = $user->save($data);
            if ($info) {
                return json(['code' => 1, 'msg' => '添加成功']);
            } else {
                return json(['code' => 2, 'msg' => '添加失败']);
            }
        }

    }

    /**
     * @api {post} /user/addBank 用户添加银行卡
     * @apiName addBank
     * @apiGroup User
     *
     * @apiParam {int} user_id 用户id
     *
     * @apiParam {String} bank_name 开户行
     * @apiParam {String} bank_card 开户账号
     * @apiParam {String} name 开户姓名
     * @apiParam {String} telephone 手机号
     *
     * @apiSuccess {String} 1 成功
     *
     * @apiErrorExample {string} Error-Response:
     * 0 : 已经添加过银行了
     * 2：添加失败
     */
    public function addBank()
    {

        $where['user_id'] = input('post.user_id');
        //验证是否已经添加
        $res = UserBankModel::where($where)->find();
        if ($res) {
            return json(['code' => 0, 'msg' => '已经添加过支付宝了']);
        } else {
            $data['user_id'] = input('post.user_id');
            $data['bank_name'] = input('post.bank_name');
            $data['bank_card'] = input('post.bank_card');
            $data['name'] = input('post.name');  //开户姓名
            $data['telephone'] = input('post.telephone');  //手机号
            $data['create_time'] = strtotime(date('Y-m-d h:i:s', time()));
            $user = new UserBankModel();
            $info = $user->save($data);
            if ($info) {
                return json(['code' => 1, 'msg' => '添加成功']);
            } else {
                return json(['code' => 2, 'msg' => '添加失败']);
            }
        }

    }


    /**
     * @api {post} /user/userAliInfo 获取用户绑定支付宝信息
     * @apiName userAliInfo
     * @apiGroup User
     *
     * @apiParam {int} user_id 用户id
     *
     *
     * @apiSuccess {String} id 支付宝id
     * @apiSuccess {String} alipay_name 支付宝用户姓名
     * @apiSuccess {String} account 支付宝账号
     * @apiSuccess {String} telephone 支付宝电话
     *
     * @apiErrorExample {string} Error-Response:
     * 0 : 暂无信息
     */
    public function userAliInfo()
    {
        $where['user_id'] = input('post.user_id');

        //获取支付宝信息
        $res = UserAliModel::where($where)->find();
        if ($res) {
            return $res;
        } else {
            return json(['code' => 0, 'msg' => '暂无信息']);
        }
    }

    /**
     * @api {post} /user/deleteAliPay 删除支付宝信息
     * @apiName deleteAliPay
     * @apiGroup User
     *
     * @apiParam {int} id  支付宝账户id
     *
     *
     * @apiSuccess {String} 1 成功
     *
     * @apiErrorExample {string} Error-Response:
     * 0 : 失败
     */
    //删除支付宝信息
    public function deleteAliPay()
    {
        $where['id'] = input('post.id');
        //删除支付宝信息
        $res = UserAliModel::where($where)->delete();
        if ($res) {
            return json(['code' => 1, 'msg' => '删除成功']);
        } else {
            return json(['code' => 0, 'msg' => '删除失败']);
        }
    }

    /**
     * @api {post} /user/userBankInfo 获取用户绑定银行卡信息
     * @apiName userBankInfo
     * @apiGroup User
     *
     * @apiParam {int} user_id 用户id
     *
     * @apiSuccess {String} id 银行id
     * @apiSuccess {String} bank_name 开户行
     * @apiSuccess {String} bank_card 开户账号
     * @apiSuccess {String} name 开户姓名
     * @apiSuccess {String} telephone 手机号
     *
     *
     * @apiErrorExample {string} Error-Response:
     * 0 : 无信息
     */
    //获取用户绑定银行卡信息
    public function userBankInfo()
    {
        $where['user_id'] = input('post.user_id');

        $res = UserBankModel::where($where)->find();
        if ($res) {
            return $res;
        } else {
            return json(['code' => 0, 'msg' => '暂无信息']);
        }
    }


    /**
     * @api {post} /user/deleteBankPay 删除银行卡信息
     * @apiName deleteBankPay
     * @apiGroup User
     *
     * @apiParam {int} id  银行账户id
     *
     *
     * @apiSuccess {String} 1 成功
     *
     * @apiErrorExample {string} Error-Response:
     * 0 : 失败
     */
    //删除银行卡信息
    public function deleteBankPay()
    {
        $where['id'] = input('post.id');

        $res = UserBankModel::where($where)->delete();
        if ($res) {
            return json(['code' => 1, 'msg' => '删除成功']);
        } else {
            return json(['code' => 0, 'msg' => '删除失败']);
        }
    }

    /**
     * @api {post} /user/userTxAliOrder 提现到支付宝
     * @apiName userTxAliOrder
     * @apiGroup User
     *
     * @apiParamExample 请求体:
     *     {
     *       "user_id": "1",
     *       "account": "支付宝账号"
     *       "money": "提现金额"
     *     }
     *
     *
     * @apiSuccess {String} code 结果码
     * @apiSuccess {String} msg  消息
     *
     * @apiSuccessExample 响应体:
     *     HTTP/1.1 200 OK
     *     {
     *       "code": "1",
     *       "msg": "成功"
     *     }
     *
     *      {
     *       "code": "2",
     *       "msg": "账户余额减少失败"
     *     }
     *
     *    {
     *       "code": "3",
     *       "msg": "体现到支付宝失败"
     *     }
     */
    //提现到支付宝
    public function userTxAliOrder()
    {
        $data['user_id'] = input('post.user_id');
        $data['account'] = input('post.account');
        $data['expend_number'] = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        $account = input('post.account'); //支付宝账号
        $data['note'] = "零钱提现--支付宝" . "(" . $account . ")"; //详细信息
        $data['money'] = "-" . input('post.money');
        $tx_money = input('post.money');
        $data['state'] = 0;
        $data['create_time'] = strtotime(date('Y-m-d h:i:s', time()));

        $money = new UserDetailMoneyModel();
        $info = $money->save($data);
        if ($info) {
            $where['id'] = input('post.user_id');
            $user_money = Db::name('user')->where($where)->sum('money');
            $data1['money'] = $user_money - $tx_money;
            $res = Db::name('user')->where($where)->update($data1);
            if ($res) {
                return json_encode(['code' => 1, 'msg' => '体现成功！']);
            } else {
                return json_encode(['code' => 2, 'msg' => '账户余额减少失败！']);
            }
        } else {
            return json_encode(['code' => 3, 'msg' => '体现支付宝失败！']);
        }

    }

    /**
     * @api {post} /user/userTxBankOrder 提现到银行
     * @apiName userTxBankOrder
     * @apiGroup User
     *
     * @apiParamExample 请求体:
     *     {
     *       "user_id": "1",
     *       "bank_name": "中国银行"
     *       "bank_card": "银行账户"
     *       "money": "体现金额"
     *     }
     *
     *
     * @apiSuccess {String} code 结果码
     * @apiSuccess {String} msg  消息
     *
     * @apiSuccessExample 响应体:
     *     HTTP/1.1 200 OK
     *     {
     *       "code": "1",
     *       "msg": "成功"
     *     }
     *
     *      {
     *       "code": "2",
     *       "msg": "账户余额减少失败"
     *     }
     *
     *    {
     *       "code": "3",
     *       "msg": "提现到银行失败"
     *     }
     *
     * @apiError UserNotFound  Theidof the User was not found.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */
    //提现到银行卡
    public function userTxBankOrder()
    {
        $data['user_id'] = input('post.user_id');
        $data['expend_number'] = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        $bank_name = input('post.bank_name');//开户行
        $data['account'] = input('post.bank_card');
        $data['note'] = "零钱提现--" . $bank_name; //详细信息
        $data['money'] = "-" . input('post.money');
        $tx_money = input('post.money'); //体现money
        $data['state'] = 0;
        $data['create_time'] = strtotime(date('Y-m-d h:i:s', time()));
//        var_dump($data);
//        die;
        $money = new UserDetailMoneyModel();
        $info = $money->save($data);
        if ($info) {
            $where['id'] = input('post.user_id');
            $user_money = Db::name('user')->where($where)->sum('money');
            $data1['money'] = $user_money - $tx_money;
            $res = Db::name('user')->where($where)->update($data1);
            if ($res) {
                return json_encode(['code' => 1, 'msg' => '体现成功！']);
            } else {
                return json_encode(['code' => 2, 'msg' => '账户余额减少失败！']);
            }
        } else {
            return json_encode(['code' => 3, 'msg' => '体现到银行失败！']);
        }
    }

    /**
     * @api {post} /user/userTxLists 提现列表
     * @apiName userTxLists
     * @apiGroup User
     *
     * @apiParamExample 请求体:
     *     {
     *       "user_id": "1",
     *     }
     *
     *
     * @apiSuccess {String} code 结果码
     * @apiSuccess {String} msg  消息
     *
     * @apiSuccessExample 响应体:
     *     HTTP/1.1 200 OK  返回数据：
     *     [{"id":1,
     *       "user_id":1,
     *       "money":"2.00",
     *      "create_time":"1970-01-01 08:00:00",
     *      "note":"",
     *      "state":0,
     *      "finish_time":0,
     *      "expend_number":"123",
     *      "money_account":""}]
     *
     *
     * @apiError UserNotFound  Theidof the User was not found.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */

    public function userTxLists()
    {
        $where['user_id'] = input('post.user_id');
        $info = UserDetailMoney::where($where)->select();
        if (!$info->isEmpty()) {
            return $info;
        } else {
            return json_encode(['code' => 0, 'msg' => '没有体现数据！']);
        }

    }

}